package cn.xiaolang.function.connection;

import java.net.UnknownHostException;

import org.bson.Document;
import org.junit.Test;

import com.mongodb.BasicDBObject;
import com.mongodb.MongoClient;
import com.mongodb.client.FindIterable;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoCursor;
import com.mongodb.client.MongoDatabase;

/**
 * Mongo链接测试
 * 
 * @version 1.3
 * @since JDK1.7
 * @author fuhw
 * @company 上海浦信科技
 * @copyright (c) 2016 Puxin technology. All rights reserved.
 * @date 2016年11月7日 上午9:39:47
 */
@SuppressWarnings("resource")
public class ConnectMongo {

	@Test
	public void testConntect() throws Exception {
		MongoClient mongoClient = new MongoClient("192.168.0.110", 27017);
		System.out.println("Mongo: " + mongoClient);
	}

	private MongoCollection<Document> ConnectorMongoDB() throws UnknownHostException {
		MongoClient mongo = new MongoClient("192.168.0.110", 27017);
		MongoDatabase db = mongo.getDatabase("gg_fund");
		MongoCollection<Document> collection = db.getCollection("test");
		return collection;
	}

	@Test
	public void testQueryAll() {
		try {
			MongoCollection<Document> connectorMongoDB = ConnectorMongoDB();
			FindIterable<Document> findIterable = connectorMongoDB.find();
			MongoCursor<Document> dbcursor = findIterable.iterator();
			while (dbcursor.hasNext()) {
				System.out.println(dbcursor.next());
			}

		} catch (UnknownHostException e) {
			e.printStackTrace();
		}
	}

	@Test
	public void testQueryBuCriteria() {
		try {
			MongoCollection<Document> connectorMongoDB = ConnectorMongoDB();
			BasicDBObject searchQuery = new BasicDBObject();
			searchQuery.put("name", "xiaolang5");
			FindIterable<Document> find = connectorMongoDB.find(searchQuery);
			MongoCursor<Document> cursor = find.iterator();
			while (cursor.hasNext()) {
				System.out.println(cursor.next());
			}
			System.out.println("Done");
		} catch (UnknownHostException e) {
			e.printStackTrace();
		}
	}

	@Test
	public void testInsert() throws UnknownHostException {
		MongoCollection<Document> connectorMongoDB = ConnectorMongoDB();
		Document document = new Document();
		document.put("name", "xiaolang");
		document.put("age", "45");
		connectorMongoDB.insertOne(document);
		testQueryAll();
	}

}
